package cn.chowx.myjfinal.util;


import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jfinal.log.Logger;

public class JsonUtil {
	private static final Logger LOG = Logger.getLogger(JsonUtil.class);
	private static ObjectMapper OBJECTMAPPER;
	
	/**
	 * 使用泛型方法,把 json 字符串转换为相应的 JavaBean 对象.
	 * (1)转换为普通JavaBean:readValue(json,T.class)
	 * (2)转为 List, 如 List<T> ,将第二个参数传递为 T
	 * [].class. 然后使用 Arrays.asList();方法得到的数组转换为特定类型的 List
	 * 
	 * @param jsonStr
	 * @param valueType
	 * @return
	 */
	public static<T> T readValue(String jsonStr, Class<T> valueType){
		if(OBJECTMAPPER == null){
			OBJECTMAPPER = new ObjectMapper();
		}
		
		try {
			return OBJECTMAPPER.readValue(jsonStr, valueType);
		} catch (JsonParseException e) {
			LOG.error(e.getMessage());
			return null;
		} catch (JsonMappingException e) {
			LOG.error(e.getMessage());
			return null;
		} catch (IOException e) {
			LOG.error(e.getMessage());
			return null;
		}
	}
	
	/**
	 * json数组转List
	 * @param jsonStr
	 * @param valueTypeRef
	 * @return
	 */
	public static<T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
		if(OBJECTMAPPER == null){
			OBJECTMAPPER = new ObjectMapper();
		}
		try {
			return OBJECTMAPPER.readValue(jsonStr, valueTypeRef);
		} catch (JsonParseException e) {
			LOG.error(e.getMessage());
			return null;
		} catch (JsonMappingException e) {
			LOG.error(e.getMessage());
			return null;
		} catch (IOException e) {
			LOG.error(e.getMessage());
			return null;
		}
	}
	
	public static String toJson(Object object){
		if(OBJECTMAPPER == null){
			OBJECTMAPPER = new ObjectMapper();
		}
		
		try {
			return OBJECTMAPPER.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			LOG.error(e.getMessage());
			return null;
		}
	}
	
	
}
